import { useAuthStore } from '../store/authStore';
import { getCurrentUser, logout } from '../api/divide/user/sdk.gen';

// 检查用户登录状态并获取最新用户信息
export const checkAuthStatus = async () => {
  const { setUser, setLoading } = useAuthStore.getState();
  
  setLoading(true);
  
  try {
    const response = await getCurrentUser();
    if (response.data?.data) {
      setUser(response.data.data);
      return true;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    // 如果cookie无效，自动登出
    useAuthStore.getState().logout();
  } finally {
    setLoading(false);
  }
  
  return false;
};

// 登出时调用后端清除cookie
export const logoutWithCookie = async () => {
  try {
    // 调用后端登出接口清除cookie
    await logout();
    useAuthStore.getState().logout();
    
    // 清除localStorage中的缓存
    localStorage.removeItem('auth-storage');
  } catch (error) {
    console.error('登出失败:', error);
    useAuthStore.getState().logout();
    // 即使后端调用失败，也清除本地缓存
    localStorage.removeItem('auth-storage');
  }
};